import re
from common.utils.random_util import RandomUtil


class StringUtil:
    @classmethod
    def rm_brace(cls, string):
        """ 去除前后大括号 """
        string = string if not re.match(r'^{.*}$', string) else string[1:-1]
        return string

    @classmethod
    def replace_all(cls, string, purpose, dest=''):
        """
        用目标字符串dest替换字符串中所有的字符purpose
        :param string:原字符串
        :param purpose: 需替换的字符串，list或tuple
        :param dest:替换后的字符串，str格式
        :return:更新后的字符串
        """
        if not isinstance(purpose, (list, tuple)):
            raise TypeError('必须是list或tuple！')
        pattern = r'|'.join(purpose)
        return re.sub(pattern, dest, string)

    @classmethod
    def rename_and_join_timestamp(cls, string):
        """
        去除大括号并拼接(时间戳)，生成随机字符串
        :param string: 需更新的字符串
        :return: 更新后的字符串
        """
        string = string if not re.match(r'^{.*}$', string) else StringUtil.rm_brace(
            string) + '(' + RandomUtil.get_timestamp() + ')'
        return string


if __name__ == '__main__':
    rows = [{'name': 'xiaoming', 'age': 18}, {'name': 'xiaohong', 'age': 20}]
    ss = [dict(filter(lambda item: item[0] != 'age', row.items())) for row in rows]
    print(ss)
    result = StringUtil.replace_all('i like dogs,because i think dogs,animals are cute', ['dogs', 'animals'], 'cats')
    print(result)
